import axios from 'axios'
import allBus from '@/core/bus'
import allLs from '@/core/ls'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE,
  timeout: 60 * 1000
})
instance.defaults.headers['x-encrypt-enable'] = false

function interceptorRequest(config) {
  const headers = config.headers || {}
  const authToken = allLs.common.token.get()
  if (config.method === 'get') {
    if (config.data) {
      config.params = config.data
    }
  }
  if (authToken) {
    config.headers.Authorization = `Bearer ${authToken}`; 
  }
  config.headers = headers
  return config
}

function interceptorResponse(res) {
  const { data } = res
  const { code } = data

  if (code === '0000') {
    return Promise.resolve(data)
  } else if (code === '401') {
    allBus.common.loginExpire.emit()
  }
  return Promise.reject(data)
}

function errorHandler(error) {
  return Promise.reject(error)
}

instance.interceptors.request.use(interceptorRequest, errorHandler)
instance.interceptors.response.use(interceptorResponse, errorHandler)

export default function request(options) {
  return instance(options)
}
